package web

import (
	"fmt"
	"local/info"
	"local/service_manager"

	"github.com/gin-gonic/gin"
)

var serviceManager *service_manager.ServiceManager = service_manager.GetServiceManager()

func ServicesList(c *gin.Context) {
	services := serviceManager.ListServices()
	c.JSON(200, services)
}

func ServiceStart(c *gin.Context) {
	name := c.Param("name")
	if err := serviceManager.StartService(name); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": fmt.Sprintf("服务 %s 启动成功", name)})
	// c.JSON(200, gin.H{"message": fmt.Sprintf("Service %s started", name)})
}

func ServiceStop(c *gin.Context) {
	name := c.Param("name")
	if err := serviceManager.StopService(name); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": fmt.Sprintf("服务 %s 停止成功", name)})
}

func ServiceStatus(c *gin.Context) {
	name := c.Param("name")
	status, err := serviceManager.GetServiceStatus(name)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"status": status})
}

func GetVersion(c *gin.Context) {
	// versionBytes, err := os.ReadFile("version.txt")
	// if err != nil {
	// 	c.JSON(400, gin.H{"error": "无法读取版本号"})
	// 	return
	// }
	// version := strings.TrimSpace(string(versionBytes))
	c.JSON(200, gin.H{"version": info.Version})
}
